package com.qire.manhua.dal.service;

import com.qire.antsbinder.dal.DataService;
import com.qire.antsbinder.dal.annotation.StrategyAnnotation;
import com.qire.antsrouter.AntsRouter;
import com.qire.antsrouter.card.FloorCard;
import com.qire.common.basic.ObjectUtil;
import com.qire.common.collect.ListUtil;
import com.qire.common.constant.Navigation;
import com.qire.common.constant.Url;
import com.qire.common.dal.WarehouseFactory;
import com.qire.manhua.dal.IComicDataDAL;
import com.qire.manhua.model.entity.ComicBookEntity;
import com.qire.manhua.model.entity.ComicComment;
import com.qire.manhua.model.viewModel.impl.ComicDetailViewModel;
import com.qire.manhua.model.vo.CollectTaskVO;
import com.qire.manhua.model.vo.ComicDetailVO;
import com.qire.manhua.model.vo.ComicDetailVO.RankInfoVO.RankItemVO;
import com.qire.manhua.model.vo.ComicDetailVO.DetailInfoVO;
import com.qire.manhua.model.vo.DirectoryVO;
import com.qire.manhua.model.vo.OkResponseVO;

public class ComicDetailService extends DataService {

    private final IComicDataDAL comicDataDAL = WarehouseFactory.create(this, IComicDataDAL.class);

    private final ComicDetailViewModel viewModel;

    public ComicDetailService(ComicDetailViewModel viewModel) {
        this.viewModel = viewModel;
    }

    /********************************************************************************************/

    /**
     * 获取漫画书籍API接口及返回刷新回调
     * @param bookId 漫画ID
     */
    public void fetchComicDetailData(int bookId) {
        comicDataDAL.fetchComicDetailData(bookId);
    }
    @StrategyAnnotation(event = Url.comicBookDetail)
    public void fetchComicDetailDataCallBack(ComicDetailVO dataVO, boolean isCache) {
        // 未获得数据
        if(ObjectUtil.isNull(dataVO)) {
            return;
        }

        if(ObjectUtil.nonNull(dataVO.detailInfo)) {
            // 获取漫画详情数据
            final DetailInfoVO detailInfoVO = dataVO.detailInfo;

            ComicBookEntity comicBookEntity = viewModel.comicBookEntity();

            // 如果漫画实体未加载过，则根据详情加载
            if(ObjectUtil.isNull(comicBookEntity)) {
                comicBookEntity = new ComicBookEntity(detailInfoVO.id, detailInfoVO.book_name);
                viewModel.loadComicBookEntity(comicBookEntity);
            }

            // 漫画相关
            comicBookEntity.whetherCollect(detailInfoVO.shelf == 1);
            comicBookEntity.loadDiscountInfo(detailInfoVO.all_free_num, detailInfoVO.all_free_mm);
            comicBookEntity.setCoverPlotVertical(detailInfoVO.book_cover);
            comicBookEntity.setEndState(detailInfoVO.isEnd());

            // 设置
            viewModel.setHistoryReadChapterIndex(detailInfoVO.lastReadChapterIndex());
            viewModel.setCoverImgPath(detailInfoVO.book_cover);
            viewModel.setComicBookTags(detailInfoVO.tags);
            viewModel.loadFreeInfo(detailInfoVO.restriction_time, detailInfoVO.restriction_title);
            viewModel.setReadChapterBtnText(detailInfoVO.read_chapter_free == 1 ? "免费阅读" : "继续阅读");

            viewModel.setFreeChapterCount(detailInfoVO.free_num, detailInfoVO.fee_start_chapter);

            viewModel.callIntroDataAction(vm -> vm.loadComicUpdateInfo(detailInfoVO.update_cycle));

            if(dataVO.shareInfo != null) {
                viewModel.setShareInfo(dataVO.shareInfo.toShareInfo());
            }

            if(detailInfoVO.tj != null) {
                viewModel.callIntroDataAction(vm -> vm.loadCountInfo(detailInfoVO.tj.read_cnt, detailInfoVO.tj.like_cnt, detailInfoVO.tj.shelf_cnt, detailInfoVO.tj.post_cnt));
            }

            if(detailInfoVO.book_intro != null) {
                viewModel.callIntroDataAction(vm -> vm.setComicBookIntroduction(detailInfoVO.book_intro));
            }

            if(detailInfoVO.copyright != null) {
                String comicBookCopyrightsInfo = String.format("本书数字版权由“%s”提供，授权本软件使用、制作、发行、若包括不良信息，请及时告知客服！", detailInfoVO.copyright.book_copyright);
                viewModel.callIntroDataAction(vm -> vm.setComicBookCopyrightsInfo(comicBookCopyrightsInfo));
            }

            fetchComicDirectoryInfo(detailInfoVO.id);
        }

        if(dataVO.commentBest != null) {
            int size = dataVO.commentBest.length;
            ComicComment[] comments = new ComicComment[size];
            for(int index = 0; index < size; index++) {
                comments[index] = dataVO.commentBest[index].toComicComment();
            }

            viewModel.callIntroDataAction(vm -> vm.loadComicComment(comments));
        }

        if(dataVO.rank != null) {
            viewModel.callIntroDataAction(introductionViewModel -> {
                introductionViewModel.loadRankInfo(dataVO.rank.bookType.cate_name + "排行榜", dataVO.rank.bookType.id);
                introductionViewModel.clearRankList();
                int index = 1;
                for(RankItemVO itemVO : dataVO.rank.loveRank) {
                    int         bookId      = itemVO.id;
                    String      bookName    = itemVO.book_name;
                    String      book_unruly = itemVO.book_unruly;
                    String[]    tags        = itemVO.tags;
                    introductionViewModel.addRankItemViewModel(index++, bookId, bookName, book_unruly, tags);
                }
                introductionViewModel.refreshRankAdapter();
            });
        }
    }

    /**
     * 获取漫画目录信息
     * @param bookId 漫画ID
     */
    public void fetchComicDirectoryInfo(int bookId) {
        comicDataDAL.fetchComicDirectoryInfo(bookId);
    }
    @StrategyAnnotation(event = Url.comicDirectoryInfo)
    public void fetchComicDirectoryInfoCallBack(DirectoryVO data, boolean isCache) {
        if(data == null) {
            return;
        }
        ComicBookEntity comicBookEntity = viewModel.comicBookEntity();
        if(comicBookEntity == null) {
            return;
        }
        //排除已经存在数据，缓存2次刷新。
        if(ListUtil.notEmpty(comicBookEntity.directoryInfoList) && isCache) {
            return;
        }
        data.updateComicBook(comicBookEntity);
        viewModel.callDirectoryDataAction(directoryViewModel -> directoryViewModel.loadComicBookEntity(comicBookEntity));
        viewModel.loadHistoryReadChapter();
    }

    /**
     * 是否添加入书架，如果已收藏再次调用则取消收藏
     * @param comicBookEntity
     */
    public void whetherJoinMyBookshelf(ComicBookEntity comicBookEntity) {
        comicDataDAL.whetherJoinMyBookshelf(comicBookEntity.id, 0);
    }
    @StrategyAnnotation(event = Url.whetherJoinMyBookshelf)
    public void whetherJoinMyBookshelfCallback(CollectTaskVO dataVO, boolean isCache) {
        if(ObjectUtil.isNull(dataVO) || dataVO.isFail()) {
            viewModel.refreshFavorite("收藏失败", "");
            return;
        }

        String resultMsg = dataVO.getResultMsg();
        String takeMsg = dataVO.getTaskMsg();
        viewModel.refreshFavorite(resultMsg, takeMsg);
    }

    /**
     * 通过广告解锁漫画章节
     * @param comicId 漫画ID
     * @param chapterId 章节ID
     */
    public void unlockChapterByAd(int comicId, int chapterId) {
        comicDataDAL.unlockChapterByAdvert(comicId, chapterId);
    }
    @StrategyAnnotation(event = Url.ComicChapterUnlockByAd)
    public void unlockChapterByAdvertCallback(OkResponseVO dataVO, boolean isCache) {
        ComicBookEntity comicBookEntity = viewModel.comicBookEntity();
        comicBookEntity.currentReadingChapters().unlock();
        AntsRouter.ROUTER.<FloorCard>buildCard(Navigation.Page.ComicReaderPage)
                .withData("comicBookEntity", comicBookEntity)
                .navigation();
    }

    /**
     * 通过购买解锁漫画章节
     * @param comicId 漫画ID
     * @param chapterId 章节ID
     * @param chapterPrice 章节价格
     * @param paymentType 支付方式
     * @param autoPay 自动购买标签
     */
    public void unlockChapterByBuy(int comicId, int chapterId, String chapterPrice, String paymentType, int autoPay) {
        comicDataDAL.unlockChapterByBuy(comicId, chapterId, chapterPrice, paymentType, autoPay);
    }
    @StrategyAnnotation(event = Url.ComicChapterUnlockByBuy)
    public void unlockChapterByBuyCallback(OkResponseVO dataVO, boolean isCache) {
        ComicBookEntity comicBookEntity = viewModel.comicBookEntity();
        comicBookEntity.currentReadingChapters().unlock();
        AntsRouter.ROUTER.<FloorCard>buildCard(Navigation.Page.ComicReaderPage)
                .withData("comicBookEntity", comicBookEntity)
                .navigation();
    }

}
